package com.truongnha.clienttn.data.servicehelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
//import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.truongnha.clienttn.presentation.temp.JSONParser;

import android.content.Context;
import android.util.Log;

public class utils {
	private static DefaultHttpClient client;

	public static String getStringJSON(String url) {
		String json = "";
		InputStream is = null;

		Log.d("URL", url);
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpResponse httpResponse = JSONParser.getThreadSafeClient()
					.execute(httpGet);

			Log.e("JSON GET", httpResponse.getStatusLine().toString() + "-");
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		// Read httpResponse to String
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.e("JSON", json);
		} catch (Exception e) {
			Log.e("Error", "Error converting result " + e.toString());
			return null;
		}
		return json;
	}

	public static JSONObject getJSONObjectByHttpGet(String url) {
		JSONObject jObj = null;
		String json = getStringJSON(url);
		if (!"".equals(json)) {
			try {
				jObj = new JSONObject(json);
			} catch (JSONException e) {
				Log.e("Error", "Error parsing data " + e.toString());
			}
		}
		return jObj;
	}

	/*
	 * Get json array from url
	 */
	public static JSONArray getJSONArrayByHttpGet(String url) {
		JSONArray jArr = null;
		String json = getStringJSON(url);

		if (!"".equals(json)) {
			try {
				jArr = new JSONArray(json);
			} catch (Exception e) {
				jArr = new JSONArray();
				Log.e("Log error", "error in json array");
				return jArr;
			}
		}
		return jArr;
	}

	public static JSONObject getJSONObjectByHttpPost(Context context,
			String url, List<NameValuePair> params) {
		JSONObject jObj = null;
		String json = "";
		InputStream is = null;
		try {
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse httpResponse = JSONParser.getThreadSafeClient()
					.execute(httpPost);
			Log.e("JSON POST", httpResponse.getStatusLine().toString() + "-");
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
			Log.e("JSON Content", is.toString());
			// List<Cookie>
			// List<Cookie> cookies = getThreadSafeClient().getCookieStore()
			// .getCookies();
			// // CookieManager.saveCookies(context, cookies);
			// if (cookies.isEmpty()) {
			// Log.e("COOKIES post: ", "Empty Cookies");
			// } else {
			// for (int i = 0; i < cookies.size(); i++) {
			// Log.e("COOKIES post: ", cookies.get(i).getName() + "--"
			// + cookies.get(i).getValue());
			// }
			// }
			Log.e("JSON", "In login user 02.6");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.e("JSON", "In login user 02.7");
		// Read httpResponse to String
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		// Try parse the string to a JSON object
		if (!json.equals("")) {
			try {
				jObj = new JSONObject(json);
				jObj.put("success", "1");
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}
		} else {
			try {
				jObj = new JSONObject();
				jObj.put("success", "0");
			} catch (JSONException e) {
				Log.e("JSON Parser", "Error parsing data " + e.toString());
			}
		}
		return jObj;
	}

	public static DefaultHttpClient getThreadSafeClient() {
		if (client != null) {
			return client;
		}
		client = new DefaultHttpClient();
		ClientConnectionManager mgr = client.getConnectionManager();

		HttpParams params = client.getParams();
		client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
				mgr.getSchemeRegistry()), params);
		return client;
	}

}
